import React from 'react'
import './AI-order.css'
import {connect,} from  'react-redux'
import {withRouter,} from 'react-router-dom'
import {Toast, WingBlank} from "antd-mobile";
import GoBackLayout from "../../layouts/GoBackLayout/GoBackLayout";
import ConfirmBtn from "../../shared-components/ConfirmBtn/ConfirmBtn";
import CoinIcon from "../../res/images/web/shared/coin.png"

import LocalStorageService from "../../utils/LocalStorageService";
import constants, {local, test} from "../../utils/constants";
import AgreeIconCheck from "../../res/images/web/game-room/choose agree-selected@2x.png"
import AgreeIconEmpty from "../../res/images/web/game-room/choose agree@2x.png"
import {Modal} from "antd-mobile";
import CancelModalIcon from "../../res/images/web/game-room/cancel@2x.png";
import CustomButton from "../../shared-components/CustomButton/CustomBotton";
import CheckIcon from "../../res/images/web/wallet/choose pay-selected@2x.png";
import UnCheckIcon from "../../res/images/web/wallet/choose@2x.png";
import WeChatIcon from "../../res/images/web/wallet/wechat 2@2x.png";
import {formatDate} from "../../utils/dateService";
import {GlobalStore} from "../../context";

class AIOrder extends React.Component {

    constructor(props) {
        super(props)
        this.state = {
            coupons: [],
            agree: true,
            modalShow: false,
            payList: [
                {title: '微信(默认)', icon: WeChatIcon, select: true,},
            ],
        }
    }

    componentDidMount() {
        const game = this.props.game.currentGame
        const matchId = this.props.match.params.matchId
        const uid = LocalStorageService.get('userid')
        this.props.doFetchGameDetail({matchId: parseInt(matchId)})
        const userDetail = this.props.user.userdetail
        const flag = userDetail.initFlag
        this.props.fetchUserDetail({uid,})
        this.props.doFetchGameAi({uid, matchId: Number(matchId),})
        // console.log(userDetail)
        this.setCoupons()
    }

    componentDidUpdate(prevProps, prevState, snapshot) {
        const flag1 = this.props.user.userdetail.initFlag
        const flag2 = prevProps.user.userdetail.initFlag

        if (flag1 !== flag2) {
            this.setCoupons()
        }
        const p1 = prevProps.user.userdetail.Packet
        const p2 = this.props.user.userdetail.Packet
        if (p1 !== p2) {
            this.setCoupons()
        }
        // const pC = pDetail.c
    }

    setCoupons = () => {
        const userDetail = this.props.user.userdetail
        const Packet = JSON.parse(userDetail.Packet)
        let cs = []

        Packet.map(item => {
            if (item[0] > 10000 && item[0] < 20000) {
                let count = item[1]
                for (let i = 0; i < count; i++) {
                    let couponItem = {}
                    couponItem.id = item[0]
                    if (i === 0) {
                        couponItem.active = true
                    } else {
                        couponItem.active = false
                    }
                    couponItem.index = i
                    cs.push(couponItem)
                }


            }
        })
        this.setState({
            coupons: cs,
        })
    }

    selectCoupon = (coupon) => {

        const cs = [...this.state.coupons]
        const i = cs.findIndex(c => c.index === coupon.index)

        for (let j = 0; j < cs.length; j++) {
            let c = cs[j]
            if (j === i) {
                c.active = !c.active
            } else {
                c.active = false
            }
        }
        this.setState({
            coupons: cs,
        })
        // onSelected(coupon, this.state.)
    }

    checkAgree = () => {
        if (this.state.agree) {
            return true
        } else {
            Toast.info('请先阅读并同意协议和政策', 1)
            return false
        }
    }


    buyAi = ({type, mark, game,}) => {
        if (this.checkAgree()) {
            const uid = localStorage.getItem('userid')
            const matchId = this.props.match.params.matchId
            let propid = 0
            for (let j = 0; j < this.state.coupons.length; j++) {
                let c = this.state.coupons[j]
                if (c.active === true) {
                    propid = c.id
                }
            }

            this.props.doBuyGameAi({
                uid,
                matchId,
                aitype: type,
                propid,
                game,
                mark,
            }).then(() => {
                this.context.user.setAIBuy(true)
                this.props.history.push('../game/' + matchId, {AIBtnClick: true, from: 'ai-order',})
            })
        }

    }

    buyAiWechat = ({type, mark}) => {
        if (this.checkAgree()) {
            const uid = LocalStorageService.get('userid')
            const style = 101
            const matchId = this.props.match.params.matchId
            let baseUrl
            // baseUrl = 'http://www.youtoball.com:8080/game/'
            if (test) {
                if (local) {
                    baseUrl = 'http://localhost:3001/game/'
                } else {
                    baseUrl = 'http://123.207.85.242:8080/game/'
                }
            } else {
                baseUrl = 'http://www.youtoball.com:8080/game/'
            }
            // const baseUrl = test ? 'http://123.207.85.242:8080/game/' : 'http://www.youtoball.com:8080/game/'
            const redirect = baseUrl + matchId + `?wechat=true&type=${type}&style=${style}`
            this.props.doWechatPay({
                uid,
                style,
                mark,
                redirect,
            })
        }
    }

    getOrderPrice = (cost) => {
        const cs = this.state.coupons
        if (cs.length === 0) {
            return cost
        }
        // const i = cs.find(c => c.active = true)
        // if (i > -1) {
        //     return cost
        // } else {
        //     const c = cs[i]
        //     const data = c.data
        //     return 0
        // }
        for (let i = 0; i < cs.length; i++) {
            let c = cs[i]
            if (c.active === true) {
                return 0
            }
        }
        return cost
    }

    render() {

        const game = this.props.game.currentGame
        const home = game.home_team
        const away = game.away_team
        const homeName = home.name_zh
        const awayName = away.name_zh

        const ai = game.ai
        const typeQ = Number(this.props.location.search.slice(-1))
        const aiM = {
            1: 'RQ',
            2: 'SFP',
            3: 'DXQ',
        }
        const type = ai[aiM[typeQ]]
        const cost = type.cost

        const userDetail = this.props.user.userdetail
        // let orderPrice
        let orderPrice = this.getOrderPrice(cost)
        const price = cost
        const Gold = userDetail.Gold
        // const enough = Gold >= price
        // const enough = false
        const free = orderPrice === 0

        const vs = `${homeName} VS ${awayName}`
        const dateObj = new Date(game.info.matchtime * 1000)
        const date = formatDate(dateObj, '-')
        const time = dateObj.toTimeString().split(' ')[0]
        const mark = `${vs} ${date} ${time}`
        const event = game.matchevent.name_zh

        // const myCoin = <div  className={`ai-order-my-coin${enough ? '-enough' : ''} flex-space-between-align-center`}>
        //     <span>我的金币</span>
        //     {enough ? <span>{Gold}</span> : <span>0.0（金币不足，请充值)</span>}
        // </div>
        const myCoin = <div  className={`ai-order-my-coin flex-space-between-align-center`}>
            <span>我的金币</span>
            <span>{Gold}</span>
            {/*{enough ?  : <span>0.0（金币不足，请充值)</span>}*/}
        </div>

        const btn = free
            ? <ConfirmBtn
                btnActive={true}
                onClick={() => this.buyAi({type: typeQ, mark: mark, game: event,})}
            >确认支付</ConfirmBtn>
            : <ConfirmBtn
                btnActive={true}
                onClick={() => {
                    if (this.checkAgree()) {
                        this.setState({modalShow: true,})
                    }
                }}
                // onClick={() => this.buyAiWechat(typeQ)}
            >确认支付</ConfirmBtn>
        // const btn = <ConfirmBtn
        //     btnActive={false}
        //     onClick={() => Toast.info('金币不够哦')}

        // >确认支付</ConfirmBtn>

        const couponMapper = {
            10001: '0折优惠券',
        }

        const couponsList = this.state.coupons.slice(0, 3)
        const remain = this.state.coupons.length

        const couponsOption = <div className='ai-order-coupons'>

            <div className='flex-space-between-align-center'>
                <p className='ai-order-coupons-title'>优惠券</p>
                {remain > 3 ? <span className='gray-text'>剩余{remain}张</span> : null}
            </div>

            {couponsList.map((c, i) => {
                return <div
                    key={i}
                    className={c.active || couponsList.some(c => c.active === true)? 'coupon-item-active' : 'coupon-item'}
                    onClick={(e) => this.selectCoupon(c)}
                >
                    <p>
                        {couponMapper[c.id]}
                    </p>
                    {/*<div className='coupon-item-dot'>*/}
                    {/*    <div/>*/}
                    {/*</div>*/}
                    <div className='coupon-item-option'>
                        <span>
                            {c.active ? '已选择' : '立即使用'}
                        </span>

                    </div>
                </div>

                // const cId = c.data[0]
                // const count = c.data[1]
                // let arr = []
                // for (let j = 0; j < count; j++) {
                //     arr.push(cId)
                // }
                // return arr.map((c, i) => {
                //     return <div
                //         key={i}
                //         className={c.active ? 'coupon-item-active' : 'coupon-item'}
                //         onClick={(e) => this.selectCoupon(c)}
                //     >
                //         <p>
                //             {couponMapper[cId]}
                //         </p>
                //         {/*<div className='coupon-item-dot'>*/}
                //         {/*    <div/>*/}
                //         {/*</div>*/}
                //         <div className='coupon-item-option'>
                //         <span>
                //             {c.active ? '已选择' : '立即使用'}
                //         </span>
                //
                //         </div>
                //     </div>
                // })

            })}
        </div>

        const payList = this.state.payList.map((pay, i) => (
            <div
                key={i}
                className={`flex-space-between-align-center pay-list-item${pay.select ? ' pay-list-item-select' : ''}`}
                onClick={(e) =>this.handlePayItemClick(pay)}
            >
                <div className='flex-center-align-center'>
                    <img src={pay.icon} alt='' style={{marginRight: '8px', height: 28, width: 28,}}/>
                    <span>微信</span>
                </div>

                <div className='flex-center-align-center'>
                    <img alt='' style={{height: 24, width: 24,}} src={pay.select ? CheckIcon : UnCheckIcon}/>
                </div>
            </div>

        ))

        const modal = <Modal
            popup
            animationType="slide-up"
            // visible={this.state.modalShow}
            // onClose={() => {
            //     this.setState({
            //         modalShow: false,
            //     })
            // }}
            visible={this.state.modalShow}
            onClose={() => this.setState({modalShow: false,})}
        >
            <div
                style={{
                    width: '100%',
                    height: '285px',
                    backgroundColor: '#fff',
                    position: 'relative',
                    padding: '14px',
                    boxSizing: 'border-box',
                }}
            >
                <img
                    style={{
                        position: 'absolute',
                        right: '16px',
                        top: '12px',
                        width: '28px',
                    }}
                    src={CancelModalIcon}
                    alt=''
                    onClick={() => this.setState({modalShow: false,})}
                />

                <p
                    style={{
                        fontSize: '18px',
                        color: 'rgba(51,51,51,1)',
                        lineHeight: '25px',
                        marginBottom: '20px',
                    }}
                >购买分析</p>

                <p
                    style={{
                        fontSize: '40px',
                        fontWeight: 'bold',
                        color: 'rgba(51,51,51,1)',
                        lineHeight: '47px',
                    }}
                >¥{price}</p>

                {/*<div className='wallet-modal'>*/}
                {/*    <p className='wallet-modal-title'>支付详情</p>*/}
                {/*    <p className='wallet-modal-price'>*/}
                {/*        <span className='wallet-modal-price-rmb'>¥ </span>*/}
                {/*        {price}*/}
                {/*    </p>*/}
                {/*</div>*/}
                <div style={{textAlign: 'left', marginBottom: '6px'}}>
                    <span className='pay-list-title'>支付方式</span>
                    {payList}
                </div>

                <div
                    style={{
                        position: 'absolute',
                        bottom: '16px',
                        width: 'calc(100% - 28px)',
                        textAlign: 'right',
                    }}
                >

                    <CustomButton
                        onClick={() => this.buyAiWechat({type: typeQ, mark, game: event,})}
                    ><span style={{letterSpacing: '12px'}}>确认支付</span></CustomButton>

                </div>

            </div>
        </Modal>


        return (
            <GoBackLayout
                history={this.props.history}
                title='订单支付'
            >
                {this.state.modalShow ? modal : null}
                {/*<div*/}
                {/*    className='inform-banner'*/}
                {/*>*/}
                {/*    <span>彩市有风险，投资需谨慎。</span>*/}
                {/*</div>*/}
                <div
                    className='shadow-page ai-order-ctn'
                >

                    <p className='ai-order-title'>订单详情</p>
                    <WingBlank>
                        <div className='ai-order-item flex-space-between-align-center'>
                            <span>商品详情</span>
                            <span>{vs}</span>
                        </div>

                        <div className='ai-order-item flex-space-between-align-center'>
                            <span>商品类型</span>
                            <span>{type.title}</span>
                        </div>

                        <div className='ai-order-item flex-space-between-align-center'>
                            <span>商品价格</span>
                            <div className='flex-center-align-center'>
                                {/*<img src={CoinIcon} alt=''/>*/}
                                <span>￥{type.cost}</span>
                            </div>

                        </div>
                    </WingBlank>

                    {/*{myCoin}*/}

                    {this.state.coupons.length > 0 ? couponsOption : null}

                    {/*{enough ? null : (*/}
                    {/*    <div*/}
                    {/*        className='ai-order-link'*/}
                    {/*        onClick={() => this.props.history.push('../wallet')}*/}
                    {/*    >*/}
                    {/*        <span>前往充值中心</span>*/}
                    {/*    </div>*/}
                    {/*)}*/}



                    <div className='ai-order-add'>
                        <span>购买须知： 分析的购买仅限于智能分析消费；一经售出不可退还； 购彩有风险，分析结果可能与最终结果不同；活动解释权归Youtoball平台所有。</span>
                    </div>

                    <div className='ai-order-agree'>
                        <img
                            src={this.state.agree ? AgreeIconCheck : AgreeIconEmpty}
                            alt=''
                            style={{
                                width: 12,
                                height: 12,
                                marginRight: 4,
                            }}
                            onClick={() => {
                                this.setState({
                                    agree: !this.state.agree,
                                })
                            }}
                        />
                        <span>支付订单视为同意YouToball的
                            <span onClick={() => this.props.history.push('../user-policy')}>《用户协议》</span>
                            和
                            <span onClick={() => this.props.history.push('../privacy-policy')}>《隐私政策》</span>
                        </span>
                    </div>

                </div>

                <div className='ai-order-bottom flex flex-space-between-align-center'>
                    <div className='ai-order-bottom-left'>
                        <p>订单金额</p>
                        <div className='flex-space-between-align-center'>
                            {/*<img src={CoinIcon} alt='' style={{marginRight: '8px'}}/>*/}
                            <span style={{
                                fontSize: '24px',
                                fontWeight: '500',
                                color: 'rgba(51,51,51,1)',
                                lineHeight: '33px',
                            }}>￥{orderPrice}</span>
                        </div>
                    </div>
                    <div>
                        {btn}
                    </div>
                </div>
            </GoBackLayout>
        )
    }


}

AIOrder.contextType = GlobalStore

const mapState = state => ({
    game: state.game,
    user: state.user,
})

const mapDispatch = dispatch => ({
    doFetchGameDetail: (payload) => dispatch.game.doFetchGameDetail(payload),
    fetchUserDetail: (id) => dispatch.user.fetchUserDetail(id),
    doBuyGameAi: payload => dispatch.game.doBuyGameAi(payload),
    doFetchGameAi: (payload) => dispatch.game.doFetchGameAi(payload),
    doWechatPay: (payload) => dispatch.user.doWechatPay(payload),
})

export default connect(mapState, mapDispatch)(withRouter(AIOrder))
